package com.tbq.game.service.utils

import java.security.MessageDigest

class Md5Util private constructor() {

    init {
        throw AssertionError()
    }

    companion object {
        /**
         * Used to build output as Hex
         */
        private val DIGITS_LOWER = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f')

        /**
         * encode By MD5
         *
         * @param str    字符串
         * @return String
         */
        fun md5(str: String?): String {
            if (str == null) {
                return ""
            }
            try {
                val messageDigest = MessageDigest.getInstance("MD5")
                messageDigest.update(str.toByteArray())
                return String(encodeHex(messageDigest.digest()))
            } catch (e: Exception) {
                throw RuntimeException(e)
            }

        }

        /**
         * Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order.
         * The returned array will be double the length of the passed array, as it takes two characters to represent any
         * given byte.
         *
         * @param data a byte[] to convert to Hex characters
         * @return A char[] containing hexadecimal characters
         */
        fun encodeHex(data: ByteArray): CharArray {
            val l = data.size
            val out = CharArray(l shl 1)
            // two characters form the hex value.
            var i = 0
            var j = 0
            while (i < l) {
                out[j++] = DIGITS_LOWER[(0xF0 and data[i].toInt()).ushr(4)]
                out[j++] = DIGITS_LOWER[0x0F and data[i].toInt()]
                i++
            }
            return out
        }
    }
}